<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/6/12
 * Time: 11:46
 */

namespace app\common\model;

use app\common\lib\exception\ApiException;
use Exception;
use think\Cache;

/**
 * 用户档案数据操作类
 * Class Recode
 * @package app\common\model
 */
class Recode extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_recode';

    public function cat()
    {
        return $this->belongsToMany('Cat', 'wechat_backup_07_18_14_43_00.app_recode_cat', 'cid', 'rid');
    }

    /**
     * 获取自己档案-走缓存
     * @param array $map
     * @return array
     * @throws Exception
     */
    public function getSelfRecode($map = [])
    {
        return (new \app\common\cachemodel\Recode())->getRecodeLists($map['uid'], 1);
    }

    /**
     * 获取档案信息
     * @param array $map
     * id int must 档案id
     * uid int  用户id
     * @return array|bool|mixed
     * @throws Exception
     */
    public function getRecode($map = [])
    {
        $data = (new \app\common\cachemodel\Recode())->getInfoById($map['id']);

        if (isset($map['uid'], $data['uid']) && $data['uid'] != $map['uid'])
        {
            \think\Log::write('getRecode：data-uid=' . $data['uid'] . ' ===== map-uid=' . $map['uid'], 'error', true);
            throw new ApiException('档案不存在');
        }
        return $data;
    }

    /**
     * 获取档案信息【用于占星师平台-星盘接口】
     * @param $rid
     * @return mixed
     * @throws Exception
     */
    public function getRecodeWithRid($rid)
    {
        return (new \app\common\cachemodel\Recode())->getInfoById($rid);
    }

    /**
     * 获取带日月升的用户信息
     * @param array $map ['id'=> 档案id]
     * @return array
     * @throws ApiException
     * @throws Exception
     */
    public function getRecodeWithAstro($map = [])
    {
        $recode = (new \app\common\cachemodel\Recode())->getInfoById($map['id']);
        try
        {
            $field = 'sun,moon,asc';// 获取日月升信息

            $recoe_astro = $this->table('wechat_backup_07_18_14_43_00.app_recode_astro')->field($field)->where(['rid' => $map['id']])->findOrFail()->toArray();

            Cache::set('recode_astro_' . $map['id'], $recoe_astro, 86400 * 1);

        }
        catch (Exception $e)
        {
            // 错误信息写入日志
            \think\Log::write($e->getMessage(), 'recode_error', true);

            throw new ApiException('档案信息获取失败');
        }

        return array_merge($recode, $recoe_astro);
    }
}
